package com.xmindguoguo.boot.modular.system.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xmindguoguo.boot.modular.system.dao.TSystemRelationDao;
import com.xmindguoguo.boot.modular.system.model.TSystemRelationModel;
import com.xmindguoguo.boot.modular.system.service.ITSystemRelationService;
import com.xmindguoguo.boot.util.CmUtil;
import com.xmindguoguo.boot.util.ConvertUtil;

/**
 * Service
 *
 * @author xmind-果果
 * @Date 2018-12-22 22:57
 */
@Service
@Transactional
public class TSystemRelationServiceImpl extends ServiceImpl<TSystemRelationDao, TSystemRelationModel> implements ITSystemRelationService {

    @Override
    public boolean saveMenuList(String ids, Long roleId) {
        boolean flag = true;
        // 进行优化,先查询出来已经拥有的,然后进行筛选 需要删除的进行删除，需要增加的进行增加
        // 先查询出来已经拥有的
        Wrapper<TSystemRelationModel> wraaper = new EntityWrapper<>();
        wraaper.eq("roleId", roleId);
        List<TSystemRelationModel> relationList = this.selectList(wraaper);
        // 需要删除的 数据库有的但是 ids中不存在的
        if (CollectionUtils.isNotEmpty(relationList)) {
            Set<Long> deleteIdSet = new HashSet<>();
            for (TSystemRelationModel model : relationList) {
                if (!ids.contains(ConvertUtil.objToString(model.getMenId()))) {
                    deleteIdSet.add(model.getId());
                }
            }
            if (!deleteIdSet.isEmpty()) {
                flag = this.deleteBatchIds(deleteIdSet);
            }
        }
        // 需要增加的进行增加 ids有的 但是数据库中不存在的
        List<Long> menuIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(relationList)) {
            for (TSystemRelationModel model : relationList) {
                menuIdList.add(model.getMenId());
            }
        }
        Long[] idsArray = ConvertUtil.StringToLongArray(ids);
        if (ArrayUtils.isNotEmpty(idsArray)) {
            List<TSystemRelationModel> list = new ArrayList<>();
            TSystemRelationModel model = null;
            for (Long menuId : idsArray) {
                if (!menuIdList.contains(menuId)) {
                    model = new TSystemRelationModel();
                    model.setId(CmUtil.getPkId());
                    model.setRoleId(roleId);
                    model.setMenId(menuId);
                    list.add(model);
                }
            }
            if (!list.isEmpty()) {
                flag = this.insertBatch(list);
            }
        }
        return flag;
    }

}
